<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中山大学刷题平台 - 首页</title>
    <!-- 外部CDN资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义Tailwind配置 -->
    <script src="{{ url_for('static', filename='js/tailwind.config.js') }}"></script>
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}">
    <link rel="icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/png">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.png') }}" type="image/png">
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .btn-sysu-outline {
                @apply border-2 border-white rounded-lg px-6 py-3 font-medium transition-all duration-300;
            }
            .card-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1;
            }
            .fade-in {
                opacity: 0;
                transform: translateY(20px);
                transition: opacity 0.1s ease-out, transform 0.1s ease-out;
            }
            .fade-in.visible {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body class="opacity-0 transition-opacity 0.8s ease-out" onload="document.body.classList.add('opacity-100')">
    <!-- 顶部导航栏（含跳转按钮） -->
    <header id="navbar" class="sticky top-0 z-50 bg-white border-b border-gray-200 transition-all duration-300 fade-in">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <!-- 校徽+平台名称 -->
                <div class="flex items-center">
                    <div class="w-10 h-10 bg-sysu-blue text-white rounded-lg flex items-center justify-center mr-3">
                        <i class="fa fa-graduation-cap text-xl"></i>
                    </div>
                    <h1 class="text-lg font-bold text-sysu-blue">中山大学刷题平台</h1>
                </div>

                <!-- 核心导航（桌面端，带跳转） -->
                <nav class="hidden md:flex space-x-6">
                    <a href="/" class="text-sysu-blue font-medium border-b-2 border-sysu-blue py-5">首页</a>
                    <a href="/questions" class="text-gray-600 hover:text-sysu-blue py-5 transition-colors">题库</a>
                    <a href="/contests" class="text-gray-600 hover:text-sysu-blue py-5 transition-colors">竞赛</a>
                    <a href="/ranking" class="text-gray-600 hover:text-sysu-blue py-5 transition-colors">排行榜</a>
                    <a href="/resources" class="text-gray-600 hover:text-sysu-blue py-5 transition-colors">学习资源</a>
                </nav>

                <!-- 用户功能区 -->
                <div class="flex items-center space-x-4">
                    <!-- 搜索框 -->
                    <div class="hidden lg:flex items-center relative">
                        <input type="text" placeholder="搜索题目/资源"
                               class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:border-sysu-blue focus:outline-none focus:ring-2 focus:ring-sysu-blue/20 w-48">
                        <i class="fa fa-search absolute left-3 text-gray-400"></i>
                    </div>

                    <!-- 用户区域容器（初始为空，由JS动态填充） -->
                    <div class="flex items-center space-x-4" id="user-area-container">
                        <!-- 加载状态 -->
                        <div class="flex items-center" id="loading-indicator">
                            <div class="w-6 h-6 border-2 border-gray-300 border-t-sysu-blue rounded-full animate-spin"></div>
                        </div>
                    </div>

                    <script>
                    // 页面加载完成后检查登录状态
                    document.addEventListener('DOMContentLoaded', function() {
                        checkLoginStatus();
                        initSmoothEffects();
                    });

                    // 检查登录状态的AJAX请求
                    async function checkLoginStatus() {
                        const container = document.getElementById('user-area-container');
                        const loadingIndicator = document.getElementById('loading-indicator');

                        try {
                            const token = localStorage.getItem('token');
                            // 发送请求到后端验证接口
                            const response = await fetch('/api/check_login', {
                                method: 'GET',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Authorization': 'Bearer ' + token
                                }
                            });

                            if (!response.ok) {
                                throw new Error('验证请求失败');
                            }

                            const data = await response.json();

                            // 根据返回的登录状态渲染不同内容
                            if (data.is_logged_in) {
                                console.log(data.avatar);
                                renderLoggedInView(container, data || {});
                            } else {
                                renderLoggedOutView(container);
                            }
                        } catch (error) {
                            console.error('登录状态验证出错:', error);
                            // 出错时默认显示登录/注册按钮
                            renderLoggedOutView(container);
                        } finally {
                            // 隐藏加载指示器
                            if (loadingIndicator) {
                                loadingIndicator.remove();
                            }
                        }
                    }

                    // 渲染已登录视图
                    function renderLoggedInView(container, userData) {
                        container.innerHTML = `
                            <div class="relative" id="userDropdown">
                                <button class="flex items-center space-x-2 focus:outline-none cursor-pointer" id="dropdownTrigger">
                                    <img src="${'http://localhost:5000/api/v1/avatar/' + userData.user_id || 'https://picsum.photos/id/1005/40/40'}"
                                         alt="${userData.username || '用户头像'}"
                                         class="w-8 h-8 rounded-full border-2 border-transparent hover:border-sysu-blue transition-colors">
                                    <i class="fa fa-angle-down text-gray-500 hidden sm:block transition-transform duration-300" id="dropdownIcon"></i>
                                </button>
                                <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 hidden z-50" id="dropdownMenu">
                                    <a href="/profile/${ userData.user_id }" class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightBlue hover:text-sysu-blue transition-colors">个人中心</a>
                                    <a href="/my_progress/${ userData.user_id }" class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightBlue hover:text-sysu-blue transition-colors">学习进度</a>
                                    <a class="block px-4 py-2 text-gray-700 hover:bg-sysu-lightBlue hover:text-sysu-blue transition-colors" onclick="logout()">退出登录</a>
                                </div>
                            </div>
                        `;

                        // 绑定下拉菜单事件
                        bindDropdownEvents();
                    }

                    // 退出登录
                    function logout() {
                        try {
                            const token = localStorage.getItem('token');
                            // 发送退出登录请求到后端
                            fetch('/api/v1/logout', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Authorization': 'Bearer ' + token
                                }
                            }).then(() => {
                                // 清除本地存储中的token
                                localStorage.removeItem('token');
                                // 刷新页面或跳转到登录页
                                window.location.href = '/';
                            });
                        }
                        catch (error) {
                            console.error('退出登录出错:', error);
                        }
                    }

                    // 渲染未登录视图
                    function renderLoggedOutView(container) {
                        container.innerHTML = `
                            <div class="flex items-center space-x-3">
                                <a href="/login" class="text-gray-600 hover:text-sysu-blue transition-colors px-3 py-2 rounded-md text-sm font-medium">
                                    登录
                                </a>
                                <a href="/register" class="bg-sysu-blue text-white hover:bg-sysu-blue/90 transition-colors px-3 py-2 rounded-md text-sm font-medium">
                                    注册
                                </a>
                            </div>
                        `;
                    }

                    // 绑定下拉菜单交互事件
                    function bindDropdownEvents() {
                        const dropdownTrigger = document.getElementById('dropdownTrigger');
                        const dropdownMenu = document.getElementById('dropdownMenu');
                        const dropdownIcon = document.getElementById('dropdownIcon');
                        const userDropdown = document.getElementById('userDropdown');

                        if (!dropdownTrigger || !dropdownMenu || !dropdownIcon) return;

                        // 点击头像按钮切换下拉菜单显示状态
                        dropdownTrigger.addEventListener('click', (e) => {
                            e.stopPropagation();
                            dropdownMenu.classList.toggle('hidden');
                            dropdownIcon.classList.toggle('rotate-180');
                        });

                        // 点击页面其他区域关闭下拉菜单
                        document.addEventListener('click', () => {
                            if (!dropdownMenu.classList.contains('hidden')) {
                                dropdownMenu.classList.add('hidden');
                                dropdownIcon.classList.remove('rotate-180');
                            }
                        });

                        // 点击下拉菜单内部不关闭
                        dropdownMenu.addEventListener('click', (e) => {
                            e.stopPropagation();
                        });

                        // 鼠标离开整个下拉区域时关闭
                        userDropdown.addEventListener('mouseleave', () => {
                            setTimeout(() => {
                                if (!dropdownMenu.matches(':hover') && !dropdownTrigger.matches(':hover')) {
                                    dropdownMenu.classList.add('hidden');
                                    dropdownIcon.classList.remove('rotate-180');
                                }
                            }, 300);
                        });
                    }

                    // 初始化平滑效果
                    function initSmoothEffects() {
                        // 导航栏显示动画
                        setTimeout(() => {
                            document.getElementById('navbar').classList.add('visible');
                        }, 100);

                        // 移动端菜单按钮事件
                        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
                        const mobileMenu = document.getElementById('mobile-menu');

                        if (mobileMenuBtn && mobileMenu) {
                            mobileMenuBtn.addEventListener('click', () => {
                                mobileMenu.classList.toggle('hidden');
                                // 添加菜单切换动画
                                if (!mobileMenu.classList.contains('hidden')) {
                                    mobileMenu.style.maxHeight = '0';
                                    mobileMenu.style.overflow = 'hidden';
                                    mobileMenu.style.transition = 'max-height 0.3s ease-out';
                                    setTimeout(() => {
                                        mobileMenu.style.maxHeight = mobileMenu.scrollHeight + 'px';
                                    }, 10);
                                } else {
                                    mobileMenu.style.maxHeight = '0';
                                }
                            });
                        }

                        // 设置滚动显示动画
                        setupScrollAnimation();
                    }

                    // 设置滚动显示动画
                    function setupScrollAnimation() {
                        const fadeElements = document.querySelectorAll('.fade-in');

                        // 初始检查可见元素
                        checkFadeElements(fadeElements);

                        // 滚动时检查可见元素
                        window.addEventListener('scroll', () => {
                            checkFadeElements(fadeElements);
                        });
                    }

                    // 检查并显示进入视口的元素
                    function checkFadeElements(elements) {
                        elements.forEach((element, index) => {
                            const rect = element.getBoundingClientRect();
                            const windowHeight = window.innerHeight || document.documentElement.clientHeight;

                            // 元素进入视口
                            if (!element.classList.contains('visible')) {
                                // 依次显示，添加延迟效果
                                setTimeout(() => {
                                    element.classList.add('visible');
                                }, index * 200);
                            }
                        });
                    }
                    </script>


                    <!-- 移动端菜单按钮 -->
                    <button class="md:hidden p-2 text-gray-600 hover:text-sysu-blue" id="mobile-menu-btn">
                        <i class="fa fa-bars text-lg"></i>
                    </button>
                </div>
            </div>

            <!-- 移动端导航（默认隐藏） -->
            <div class="md:hidden hidden pb-4" id="mobile-menu">
                <div class="flex items-center relative mb-4">
                    <input type="text" placeholder="搜索题目/资源"
                           class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:border-sysu-blue focus:outline-none focus:ring-2 focus:ring-sysu-blue/20 w-full">
                    <i class="fa fa-search absolute left-3 text-gray-400"></i>
                </div>
                <nav class="flex flex-col space-y-3">
                    <a href="#" class="text-sysu-blue font-medium px-2 py-2 bg-sysu-lightBlue/50 rounded">首页</a>
                    <a href="/questions" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightBlue hover:text-sysu-blue rounded transition-colors">题库</a>
                    <a href="/contests" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightBlue hover:text-sysu-blue rounded transition-colors">竞赛</a>
                    <a href="/ranking" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightBlue hover:text-sysu-blue rounded transition-colors">排行榜</a>
                    <a href="/resources" class="text-gray-600 px-2 py-2 hover:bg-sysu-lightBlue hover:text-sysu-blue rounded transition-colors">学习资源</a>
                </nav>
            </div>
        </div>
    </header>

    <main>
        <!-- 1. 英雄区（核心功能入口） -->
        <section class="bg-gradient-to-r from-sysu-blue to-sysu-darkBlue text-white py-16 md:py-24 fade-in">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <div class="max-w-3xl">
                    <h2 class="text-[clamp(2rem,5vw,3rem)] font-bold mb-6 leading-tight">
                        提升编程能力，<br>从刷题开始
                    </h2>
                    <p class="text-white/90 text-lg mb-8 max-w-2xl">
                        覆盖算法、数据结构、编程基础等精选内容，支持多语言提交，助力中大学子夯实编程基础
                    </p>
                    <!-- 核心跳转按钮组 -->
                    <div class="flex flex-wrap gap-4">
                        <a href="/questions" class="btn-sysu-outline text-white hover:bg-white/20 flex items-center text-base transform transition-transform hover:scale-105">
                            <i class="fa fa-list-ul mr-2"></i> 进入题库
                        </a>
                        <a href="/contests" class="btn-sysu-outline text-white hover:bg-white/20 flex items-center text-base transform transition-transform hover:scale-105">
                            <i class="fa fa-trophy mr-2"></i> 参与竞赛
                        </a>
                        <a href="/resources" class="btn-sysu-outline text-white hover:bg-white/20 flex items-center text-base transform transition-transform hover:scale-105">
                            <i class="fa fa-book mr-2"></i> 学习资源
                        </a>
                    </div>
                </div>
            </div>
        </section>

        <!-- 2. 个人学习数据卡片 -->
        <section class="py-10 bg-white">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <h3 class="text-xl font-bold text-gray-800 mb-8 text-center fade-in">我的学习进度</h3>
                <!-- 四宫格数据卡片 -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    <!-- 已完成题目 -->
                    <div class="bg-sysu-gray rounded-xl p-6 card-hover text-center fade-in">
                        <div class="w-14 h-14 bg-sysu-blue/10 text-sysu-blue rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-check-circle text-2xl"></i>
                        </div>
                        <h4 class="text-3xl font-bold text-gray-800 mb-2" id="completed-questions"></h4>
                        <p class="text-gray-500 text-sm">已完成题目</p>

                    </div>

                    <!-- 提交正确率 -->
                    <div class="bg-sysu-gray rounded-xl p-6 card-hover text-center fade-in">
                        <div class="w-14 h-14 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-line-chart text-2xl"></i>
                        </div>
                        <h4 class="text-3xl font-bold text-gray-800 mb-2" id="accuracy"></h4>
                        <p class="text-gray-500 text-sm">提交正确率</p>
                        <p class="text-green-600 text-xs mt-4 flex items-center justify-center">
                            <i class="fa fa-arrow-up mr-1"></i>
                        </p>
                    </div>

                    <!-- 参与竞赛 -->
                    <div class="bg-sysu-gray rounded-xl p-6 card-hover text-center fade-in">
                        <div class="w-14 h-14 bg-yellow-100 text-yellow-600 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-trophy text-2xl"></i>
                        </div>
                        <h4 class="text-3xl font-bold text-gray-800 mb-2" id="contests_count"></h4>
                        <p class="text-gray-500 text-sm">参与竞赛</p>
                    </div>

                    <!-- 校内排名 -->
                    <div class="bg-sysu-gray rounded-xl p-6 card-hover text-center fade-in">
                        <div class="w-14 h-14 bg-sysu-lightBlue text-sysu-blue rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-star text-2xl"></i>
                        </div>
                        <h4 class="text-3xl font-bold text-gray-800 mb-2" id="ranking"></h4>
                        <p class="text-gray-500 text-sm">校内排名</p>
                    </div>
                </div>
            </div>
        </section>

        <script>
            const completed_questions = document.getElementById('completed-questions');
            const accuracy = document.getElementById('accuracy');
            const contests_count = document.getElementById('contests_count');
            const ranking = document.getElementById('ranking');
            const token = localStorage.getItem('token');
            try {
                response = fetch('/api/v1/user_info', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }
                }).then(res => res.json()).then(data => {
                    if(data.code === 200) {
                        completed_questions.innerHTML = data.completed_questions;
                        accuracy.innerHTML = data.accuracy;
                        contests_count.innerHTML = data.contests_count;
                        ranking.innerHTML = data.ranking;
                        if (data.ranking === 0) {
                            ranking.innerHTML = '未排名';
                        }
                    } else {
                        completed_questions.innerHTML = '0';
                        accuracy.innerHTML = '0';
                        contests_count.innerHTML = '0';
                        ranking.innerHTML = '未排名';
                    }
                    accuracy.innerHTML += '%';

                    // 数据加载后添加数字增长动画
                    animateValue(completed_questions, 0, parseInt(completed_questions.textContent), 1500);
                    animateValue(accuracy, 0, parseInt(accuracy.textContent), 1500);
                    animateValue(contests_count, 0, parseInt(contests_count.textContent), 1500);
                    if (ranking.textContent !== '未排名') {
                        animateValue(ranking, 0, parseInt(ranking.textContent), 1500);
                    }
            })
            } catch (error) {
                console.error('Error fetching user info:', error);
            }

            // 数字增长动画
            function animateValue(element, start, end, duration) {
                let startTimestamp = null;
                const step = (timestamp) => {
                    if (!startTimestamp) startTimestamp = timestamp;
                    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
                    // 使用缓动函数使动画更自然
                    const easeProgress = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress);
                    const value = Math.floor(easeProgress * (end - start) + start);

                    if (element.id === 'accuracy') {
                        element.textContent = value + '%';
                    } else {
                        element.textContent = value;
                    }

                    if (progress < 1) {
                        window.requestAnimationFrame(step);
                    }
                };
                window.requestAnimationFrame(step);
            }
        </script>

        <!-- 3. 核心功能入口卡片 -->
        <section class="py-12 bg-gray-50">
            <div class="container mx-auto px-4 sm:px-6 lg:px-8">
                <h3 class="text-xl font-bold text-gray-800 mb-8 text-center fade-in">平台核心功能</h3>
                <!-- 三宫格功能卡片 -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                    <!-- 题库功能 -->
                    <a href="/questions" class="block">
                        <div class="bg-white rounded-xl p-8 card-hover h-full flex flex-col items-center text-center fade-in">
                            <div class="w-16 h-16 bg-sysu-blue/10 text-sysu-blue rounded-full flex items-center justify-center mb-6">
                                <i class="fa fa-book text-2xl"></i>
                            </div>
                            <h4 class="text-xl font-bold text-gray-800 mb-3">海量题库</h4>
                            <p class="text-gray-500 mb-6 flex-grow">
                                1000+道精选题目，按难度、类型分类，满足不同学习阶段需求
                            </p>
                            <span class="text-sysu-blue font-medium flex items-center group-hover:translate-x-1 transition-transform">
                                进入题库 <i class="fa fa-angle-right ml-2"></i>
                            </span>
                        </div>
                    </a>

                    <!-- 竞赛功能 -->
                    <a href="/contests" class="block">
                        <div class="bg-white rounded-xl p-8 card-hover h-full flex flex-col items-center text-center fade-in">
                            <div class="w-16 h-16 bg-yellow-100 text-yellow-600 rounded-full flex items-center justify-center mb-6">
                                <i class="fa fa-flag text-2xl"></i>
                            </div>
                            <h4 class="text-xl font-bold text-gray-800 mb-3">编程竞赛</h4>
                            <p class="text-gray-500 mb-6 flex-grow">
                                校内/省级竞赛，ACM/IOI双赛制，以赛促学提升实战能力
                            </p>
                            <span class="text-sysu-blue font-medium flex items-center group-hover:translate-x-1 transition-transform">
                                查看竞赛 <i class="fa fa-angle-right ml-2"></i>
                            </span>
                        </div>
                    </a>

                    <!-- 学习资源功能 -->
                    <a href="/resources" class="block">
                        <div class="bg-white rounded-xl p-8 card-hover h-full flex flex-col items-center text-center fade-in">
                            <div class="w-16 h-16 bg-green-100 text-green-600 rounded-full flex items-center justify-center mb-6">
                                <i class="fa fa-video-camera text-2xl"></i>
                            </div>
                            <h4 class="text-xl font-bold text-gray-800 mb-3">学习资源</h4>
                            <p class="text-gray-500 mb-6 flex-grow">
                                算法教程、视频课程、面试真题，配套学习资料助力巩固基础
                            </p>
                            <span class="text-sysu-blue font-medium flex items-center group-hover:translate-x-1 transition-transform">
                                浏览资源 <i class="fa fa-angle-right ml-2"></i>
                            </span>
                        </div>
                    </a>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-12 fade-in">
        <div class="container mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-6 md:mb-0">
                    <div class="flex items-center">
                        <div class="w-10 h-10 bg-white text-sysu-blue rounded-lg flex items-center justify-center mr-3">
                            <i class="fa fa-graduation-cap text-xl"></i>
                        </div>
                        <h2 class="text-lg font-bold">中山大学刷题平台</h2>
                    </div>
                    <p class="text-gray-400 text-sm mt-2">助力中大学子提升编程能力</p>
                </div>
                <div class="flex space-x-6">
                    <a href="#" class="text-gray-400 hover:text-white transition-colors duration-300">
                        <i class="fa fa-question-circle mr-1"></i> 帮助中心
                    </a>
                    <a href="#" class="text-gray-400 hover:text-white transition-colors duration-300">
                        <i class="fa fa-envelope mr-1"></i> 联系我们
                    </a>
                    <a href="#" class="text-gray-400 hover:text-white transition-colors duration-300">
                        <i class="fa fa-shield mr-1"></i> 隐私政策
                    </a>
                </div>
            </div>
            <div class="border-t border-gray-700 mt-8 pt-8 text-center text-gray-400 text-sm">
                &copy; 2023 中山大学刷题平台. 所有权利保留.
            </div>
        </div>
    </footer>
</body>
</html>
